package com.apkcore.core

import android.os.Handler
import android.os.Looper
import android.view.View

object DoubleClickListener {

    private const val DOUBLE_CLICK_TIME_DELTA = 300L // milliseconds
    private var lastClickTime = 0L
    private val handler by lazy { Handler(Looper.getMainLooper()) }

//    interface OnDoubleClickListener {
//        fun onClick(v: View, count: Int)
//    }


    fun setOnSingleAndDoubleClickListener(view: View, doubleClickListener: (View, Int)->Unit) {
        val runnable by lazy {
            Runnable {
                doubleClickListener.invoke(view, 1)
            }
        }

        view.setOnClickListener {
            val clickTime = System.currentTimeMillis()
            if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA) {
                // 取消单击事件的延迟回调
                handler.removeCallbacks(runnable)
                doubleClickListener.invoke(it, 2)
            } else {
                // 延迟执行单击事件回调
                handler.postDelayed(runnable, DOUBLE_CLICK_TIME_DELTA)
            }
            lastClickTime = clickTime
        }
    }
}